import json
import logging

from settings import default_settings as Settings
from user import User


def main():
    Settings.data_dir.mkdir(exist_ok=True)
    with Settings.users_path.open('r', encoding='utf-8') as f:
        users = json.load(f)
    for user_data in users:
        try:
            user = User(user_data)
            if not user.login():
                logging.error(user_data['login']['name'] + ' 登陆失败')
                continue
            logging.info(f'Hello, {user.username}')
            user.farm()
            if not user.signed:
                user.sign()
            else:
                logging.info('今日已签到')
        except Exception as e:
            logging.error("错误！", e)
    if Settings.users_path2.exists():
        Settings.users_path2.unlink()
    Settings.users_path.rename(Settings.users_path2)
    with Settings.users_path.open('w', encoding='utf-8') as f:
        json.dump(users, f, ensure_ascii=False, indent='    ')


if __name__ == '__main__':
    main()
